package com.qpx.userservice.web;


import com.qpx.common.dto.UserDto;
import com.qpx.common.utils.Md5Util;
import com.qpx.common.vo.ResultEntity;
import com.qpx.userservice.dao.UserDao;
import com.qpx.userservice.entity.TUserEnity;
import com.qpx.userservice.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public ResultEntity login(UserDto userDto, HttpServletRequest request){
        TUserEnity byUserName = userService.findByUserName(userDto.getUsername());
        if (byUserName==null){
            return ResultEntity.error("用户不存在");
        }
        String password = Md5Util.md5(userDto.getPassword());
        if (!password.equalsIgnoreCase(byUserName.getPassword())){
            return ResultEntity.error("密码错误");
        }

        BeanUtils.copyProperties(byUserName,userDto);
        request.getSession().setAttribute("user",userDto);
        return ResultEntity.ok("登录成功",request.getSession().getId());
    }


    @RequestMapping("/registry")
    public ResultEntity registry(UserDto userDto){

        TUserEnity byUserName = userService.findByUserName(userDto.getUsername());
        if (byUserName!=null){
            return ResultEntity.error("用户名已经存在");
        }
        TUserEnity tUserEnity = new TUserEnity();
        tUserEnity.setUsername(userDto.getUsername());
        String password = Md5Util.md5(userDto.getPassword());
        tUserEnity.setPassword(password);
        userService.add(tUserEnity);
        return ResultEntity.ok("注册成功");
    }

}
